import React, {useState} from 'react';
import { useMedia } from 'react-use';
import SearchTagBar from "./SearchTagBar";
import Logo from '../assets/logoAdmin.svg';
import LogoSimple from '../assets/logoSimple.svg';
import {
    Button,
    Col,
    Drawer,
    Form,
    Input,
    message, Modal, Progress,
    Radio,
    Row,
    Select,
    Space,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
import TextArea from "antd/es/input/TextArea";
import { UploadOutlined } from '@ant-design/icons';
import {postDataAdmin} from "../apis/api";
import {useNavigate} from "react-router-dom";
import {RcFile} from "antd/es/upload";

interface NavProps {
    updateSearch: (searchTag: string, status: number|null) => void;
    updateResult: () => void;
}
const Navbar: React.FC<NavProps> = ({updateSearch , updateResult}) => {
    const shortScreen = useMedia( '(max-width: 1000px)' );

    const logoSrc = shortScreen ? LogoSimple : Logo;

    const [open, setOpen] = useState(false);
    const [uploading, setUploading] = useState(false);
    const [progress, setProgress] = useState(0);
    const [currentFile, setCurrentFile] = useState<string | null>(null);

    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const navigate = useNavigate();
    // 跳转到前台主页
    const jumpHome = () => {
        navigate('/');
    };
    const handleFileChange: UploadProps['onChange'] = (info) => {
        const newFileList = info.fileList.map(file => {
            if (file.response) {
                // 修改 file 状态为 done
                file.status = 'done';
            }
            return file;
        });
        setFileList(newFileList);
    };

    const customRequest = ({ file, onSuccess }: any) => {
        // 使用 setTimeout 模拟文件上传并立即调用 onSuccess
        setTimeout(() => {
            onSuccess('ok');
        }, 0);
    };
    const showDrawer = () => {
        setOpen(true);
    };

    const onClose = () => {
        setOpen(false);
    };
    const [form] = Form.useForm();


    //旧版上传壁纸
    // const onCreateSubmit = async () => {
    //     try {
    //         // 进行表单字段的验证
    //         const values = await form.validateFields();
    //         // 对每一个文件调用管理员-创建壁纸接口
    //         const fileSize = values.file.fileList.length;
    //         let i = 0;
    //
    //         setUploading(true);
    //
    //         for (i = 0; i < fileSize; i++) {
    //
    //             await postDataAdmin('/admin/wallpaper/create',
    //                 {
    //                     file: values.file.fileList[i].originFileObj,
    //                     name : values.name,
    //                     description : values.description,
    //                     tag : values.tag,
    //                     score : values.score,
    //                     status : values.status,
    //                 });
    //         }
    //
    //         setOpen(false);
    //     } catch (errorInfo) {
    //         // 处理验证失败的情况
    //         console.error(errorInfo)
    //         setUploading(false);
    //         message.open({
    //             type: 'error',
    //             content: '壁纸上传失败',
    //         });
    //     } finally {
    //         message.open({
    //             type: 'success',
    //             content: '壁纸上传完成',
    //         });
    //         updateResult();
    //         setUploading(false);
    //     }
    // };

    // 新版上传壁纸（带有本地进度条）
    const onCreateSubmit = async () => {
        try {
            const values = await form.validateFields();
            const fileList = values.file.fileList;

            setUploading(true);
            setProgress(0);

            for (const file of fileList) {
                await uploadFile(values, file.originFileObj as RcFile);
            }

            message.success('壁纸上传完成');
            setUploading(false);
            setProgress(100);
            setCurrentFile(null);
        } catch (errorInfo) {
            console.error(errorInfo);
            message.error('壁纸上传失败');
            setUploading(false);
        }
    };

    const uploadFile = (values: any, file: RcFile) => {
        // 由于这个请求需要进度条，所以没有写在api.ts里面
        const baseUrl = "http://192.169.3.10:9814/"
        const baseUrlLocal = "http://192.169.3.104:8080/"
        const authToken = '6667ad12c97c0815460764da';

        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('name', values.name);
            formData.append('description', values.description);
            formData.append('tag', values.tag);
            formData.append('score', values.score);
            formData.append('status', values.status);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', baseUrl+'admin/wallpaper/create', true);

            // 设置 Authorization 请求头
            xhr.setRequestHeader('Authorization', `${authToken}`);

            xhr.upload.onprogress = (event: ProgressEvent) => {
                if (event.lengthComputable) {
                    const percent = Math.round((event.loaded / event.total) * 100);
                    setProgress(percent);
                    setCurrentFile(file.name);
                }
            };

            xhr.onload = () => {
                if (xhr.status === 200) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.response);
                }
            };

            xhr.onerror = () => {
                reject(xhr.response);
            };

            xhr.send(formData);
        });
    };


    return (
        <header className="navbar">
            <div style={{position:"absolute", left:"15px"}}>
                <img className="logoIcon" src={logoSrc} alt="logo"></img>
            </div>
            <SearchTagBar updateSearch={updateSearch}></SearchTagBar>
            <Button type={"primary"}
                style={{marginRight:"20px"}}
                onClick={showDrawer}>上传
            </Button>
            <Button style={{marginRight:"5%"}}
                    onClick={jumpHome}>前台
            </Button>

            <Drawer title="壁纸编辑" onClose={onClose} open={open}
                    extra={
                        <Space>
                            <Button onClick={onClose}>取消</Button>
                            <Button onClick={onCreateSubmit} type="primary" disabled={uploading}>
                                保存
                            </Button>
                        </Space>
                    }>
                <Modal
                    visible={uploading}
                    footer={null}
                    closable={false}
                    centered
                >
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                        <p>{currentFile ? `正在上传: ${currentFile}` : '准备上传...' }</p>
                        <Progress percent={progress} status="active" />
                        <span style={{color:"#777"}}>
                            提示：本进度条只能监视从本地上传到服务器的进度，但是服务器还要将壁纸文件转存到云端，所以上传完成后还需要等待一会...
                        </span>
                    </div>
                </Modal>

                <Form layout="vertical" form={form}
                    initialValues={{
                        score: 0,
                        status: 1}}>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item name="file" label="上传壁纸">
                                <Upload
                                    name="wallpaper"
                                    accept="image/jpeg,image/jpg,image/png,image/bmp,image/webp,image/jfif,video/mp4"
                                    fileList={fileList}
                                    onChange={handleFileChange}
                                    customRequest={customRequest}
                                >
                                    <Button>
                                        <UploadOutlined /> 点击上传
                                    </Button>
                                </Upload>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="name"
                                label="壁纸名称"
                            >
                                <Input placeholder="壁纸的标题"/>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="tag"
                                label="标签"
                            >
                                <Input placeholder="壁纸的标签，逗号分割" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="description"
                                label="描述"
                            >
                                <TextArea placeholder="壁纸详细描述" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="score"
                                label="初始分数"
                            >
                                <Input placeholder="壁纸的初始官方分数，越高排名越靠前" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="status"
                                label="状态"
                            >
                                <Radio.Group>
                                    <Radio value={0}>审核中</Radio>
                                    <Radio value={1}>通过</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Drawer>
        </header>
    );
};

export default Navbar;